import { useState } from 'react';
import { useForm } from '@tanstack/react-form';
import { useNavigate } from 'react-router-dom';
import { PhoneIcon, CheckIcon, LockClosedIcon } from '@heroicons/react/24/outline';
import type { FieldApi } from '@tanstack/react-form';

import Button from '../../components/ui/Button';
import Input from '../../components/ui/Input';
import loginApis from '../../apis/auth/login';
import meStore from '../../store/me';
import { toastError } from '../../components/toast-error';
import OnlyIfUnauthenticated from '../../components/biz/OnlyIfUnauthenticated';
import Card from '../../components/ui/Card';
import VcodeButton from '../../components/util/VcodeButton';

export default function LoginPage() {
  return (
    <OnlyIfUnauthenticated>
      <LoginForm />
    </OnlyIfUnauthenticated>
  );
}

function LoginForm() {
  const navigate = useNavigate();

  const form = useForm({
    defaultValues: {
      phone: '',
      vcode: '',
      password: '',
    },
    onSubmit: ({ value }) => {
      // TODO: loading
      meStore.setState(() => ({ state: 'loading' }));
      loginApis
        .login({ phone: value.phone, vcode: value.vcode, password: value.password })
        .then((res) => {
          meStore.setState(() => ({ state: 'authenticated', me: res }));
          navigate('/me');
        })
        .catch((err) => {
          meStore.setState(() => ({ state: 'unauthenticated' }));
          toastError(err);
        });
    },
  });

  const [phone, setPhone] = useState('');

  return (
    <div>
      <h2>注册</h2>
      <div className="flex min-h-full flex-1 flex-col justify-center px-6 py-12 lg:px-8">
        <div className="mt-6 sm:mx-auto sm:w-full sm:max-w-sm">
          <Card noPadding className="px-8 py-12">
            <h2 className="mb-6 text-center text-2xl font-bold tracking-tight text-gray-900">在此登录</h2>
            <form.Provider>
              <form
                className="space-y-6"
                onSubmit={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  void form.handleSubmit();
                }}
              >
                <form.Field
                  name="phone"
                  validators={{
                    onChange: ({ value }) => {
                      if (!value) return '手机号不能为空';
                      if (!/^1[3-9]\d{9}$/.test(value)) return '手机号格式不正确';
                      return undefined;
                    },
                  }}
                  children={(field) => {
                    return (
                      <div>
                        <div className="mt-2 relative">
                          <div className=" absolute flex items-center inset-y-0 pl-3 ">
                            <PhoneIcon className="w-4 h-4" />
                          </div>
                          <Input
                            block
                            name={field.name}
                            autoComplete="new-password"
                            type="text"
                            className="pl-9"
                            value={field.state.value}
                            onBlur={field.handleBlur}
                            onChange={(e) => {
                              setPhone(e.target.value);
                              field.handleChange(e.target.value);
                            }}
                            required
                            placeholder="请在此输入手机号"
                          />
                        </div>
                        <FieldInfo field={field} />
                      </div>
                    );
                  }}
                />

                <form.Field
                  name="vcode"
                  validators={{
                    onChange: ({ value }) => {
                      if (!value) return '验证码不能为空';
                      if (!/^\d{6}$/.test(value)) return '验证码格式不正确';
                      return undefined;
                    },
                  }}
                  children={(field) => {
                    return (
                      <div>
                        <div className="mt-2 flex relative">
                          <div className=" absolute flex items-center inset-y-0 pl-3 ">
                            <CheckIcon className="w-4 h-4" />
                          </div>
                          <Input
                            name={field.name}
                            block
                            autoComplete="new-password"
                            type="text"
                            noRound
                            className="rounded-l-md pl-9"
                            value={field.state.value}
                            onBlur={field.handleBlur}
                            onChange={(e) => field.handleChange(e.target.value)}
                            required
                            placeholder="请输入验证码"
                          />
                          <VcodeButton phone={phone} sendVcodeApi={loginApis.sendVcode} />
                        </div>
                        <FieldInfo field={field} />
                      </div>
                    );
                  }}
                />

                <form.Field
                  name="password"
                  validators={{
                    onChange: ({ value }) => {
                      if (!value) return '密码不能为空';
                      if (!/^[a-zA-Z0-9`~!@#$%^&*()_+-=[\]{}\\|:;"'<,>.?/]{8,32}$/.test(value)) return '密码格式不正确';
                      return undefined;
                    },
                  }}
                  children={(field) => {
                    return (
                      <div>
                        <div className="mt-2 relative">
                          <div className=" absolute flex items-center inset-y-0 pl-3 ">
                            <LockClosedIcon className="w-4 h-4" />
                          </div>
                          <Input
                            name={field.name}
                            type="password"
                            autoComplete="new-password"
                            block
                            className="pl-9"
                            value={field.state.value}
                            onBlur={field.handleBlur}
                            onChange={(e) => field.handleChange(e.target.value)}
                            required
                            placeholder="请输入密码"
                          />
                        </div>
                        <FieldInfo field={field} />
                      </div>
                    );
                  }}
                />

                <form.Subscribe
                  selector={(state) => [state.canSubmit, state.isSubmitting]}
                  children={([canSubmit, isSubmitting]) => {
                    return (
                      <div>
                        <Button type="submit" className="flex w-full justify-center">
                          登录 {isSubmitting} {canSubmit}
                        </Button>
                      </div>
                    );
                  }}
                />
              </form>
            </form.Provider>

            <p className="mt-10 text-center text-sm text-gray-500">
              忘记密码？{' '}
              <a href="#" className="font-semibold leading-6 text-indigo-600 hover:text-indigo-500">
                戳这里重置密码
              </a>
            </p>
          </Card>
        </div>
      </div>
    </div>
  );
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function FieldInfo({ field }: { field: FieldApi<any, any, any, any> }) {
  return (
    <>
      {field.state.meta.touchedErrors ? <em>{field.state.meta.touchedErrors}</em> : null}
      {field.state.meta.isValidating ? 'Validating...' : null}
    </>
  );
}
